import PlayName from '@/component/PlayName'
import { Button } from 'antd'
import { useSelector } from 'react-redux'
import { Socket } from 'socket.io-client'
import { useMemo } from 'react';

export default function PlayerList({ socketRef }: { socketRef: React.MutableRefObject<Socket | null> }) {
    const players = useSelector(({ main }: any) => {
        return main.players
    })

    function finishReady() {
        socketRef.current?.emit('finishReady')
    }
    function startGame() {
        socketRef.current?.emit('startGame')
    }

    const { isReady, isMaster, allReady } = useMemo(() => {
        const obj = {
            isReady: false, isMaster: false, allReady: true
        }
        if (socketRef.current !== null) {
            const { id } = socketRef.current
            players.forEach((player: any) => {
                const { isReady } = player
                if (isReady === false) obj.allReady = false
                if (player.id === id) {
                    const { isMaster, isReady } = player
                    obj.isMaster = isMaster
                    obj.isReady = isReady
                }
            })
        }
        return obj
    }, [socketRef.current, players])


    return (
        <div style={{ marginBottom: 4, width: 300, height: 800, backgroundColor: "white", overflow: 'auto', color: 'black' }}>
            {players.map((player: any) => {
                const {id,isReady}=player
                return <div style={{ margin: 5 }} key={id}>
                    <PlayName {...player} />
                    {isReady?"准备好了":"请稍等"}
                </div>
            })}
            {!isReady && <Button type="primary" onClick={finishReady}>准备好了</Button>}
            {isMaster && allReady && <Button type="primary" onClick={startGame}>开始游戏</Button>}
        </div>
    )
}
